package com.cg.system.interceptors;

import com.cg.system.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;


@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 从请求头中获取令牌
        String token = request.getHeader("Authorization");

        if (token == null || token.isEmpty()) {
            response.setStatus(401); // 未授权
            return false;
        }

        try {
            // 使用JwtUtil解析token
            Map<String, Object> claims = JwtUtil.parseToken(token);

            // 从claims中获取用户名（假设claims中包含username字段）
            String username = (String) claims.get("username");

            if (username == null) {
                response.setStatus(401); // 无效的token
                return false;
            }

            // 验证token是否存在于Redis中（可选步骤，取决于业务需求）
            ValueOperations<String, String> valueOps = stringRedisTemplate.opsForValue();
            String redisUsername = valueOps.get(token);

            if (redisUsername == null || !redisUsername.equals(username)) {
                response.setStatus(401); // token不存在或不匹配
                return false;
            }

            // 将用户名存储到请求属性中，供后续使用
            request.setAttribute("username", username);

            return true;
        } catch (Exception e) {
            response.setStatus(401); // token解析失败
            return false;
        }
    }

//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//       //清空ThreadLocal中的数据
//        ThreadLocalUtil.remove();
//    }
}
